import 'dart:async';
import 'dart:math' as math;
import '../MyConfig.dart';
import 'package:flutter/material.dart';
import 'package:tetris/gamer/gamer.dart';

/// 手柄控制界面
class GameController extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: 240,
      child: Row(
        children: <Widget>[
          Spacer(flex: 1),
          DirectionController() ,
          Spacer(flex: 2),
          ChangeController(),
          Spacer(flex: 1),
        ],
      ),
    );
  }
}

const Size _DIRECTION_BUTTON_SIZE = const Size(48, 48);
const Size _SYSTEM_BUTTON_SIZE = const Size(28, 28);
const double _DIRECTION_SPACE = 25; //40
const double _iconSize = 16;

class DirectionController extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var angleChange = math.pi /4.0 ;
    var directs=  Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[

        Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            //上
            Transform.rotate(
                angle: -angleChange,
                child: Icon(
                  Icons.arrow_drop_up,
                  color: Colors.red,
                  size: _iconSize,
                )),
            // 下
            Transform.rotate(
                angle:  -angleChange,
                child: Icon(
                  Icons.arrow_right,
                  color: Colors.red,
                  size: _iconSize,
                )),
          ],
        ),

        Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            // 左
            Transform.rotate(
                angle: -angleChange,
                child: Icon(
                  Icons.arrow_left,
                  color: Colors.red,
                  size: _iconSize,
                )),
            // 下
            Transform.rotate(
                angle:  -angleChange,
                child: Icon(
                  Icons.arrow_drop_down,
                  color: Colors.red,
                  size: _iconSize,
                )),
          ],
        ),
      ],
    ) ;


    var directView = Stack(
      alignment: Alignment.center,
      children: <Widget>[
        // SizedBox.fromSize(size: _DIRECTION_BUTTON_SIZE * 2.8),
        // 上下左右 方向提示  .
        // todo 这个布局很巧妙 ，可以学习一下。
        Transform.rotate(
          angle: angleChange, // angleChange
          child: Transform.scale(
            scale: 1 ,
            child: directs ,
          ) ,
        ),
        // 上下左右按钮
        Transform.rotate(
          angle: angleChange  ,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  _Button(
                      enableLongPress: false,
                      size: _DIRECTION_BUTTON_SIZE,
                      onTap: () {
                        Game.of(context).rotate();
                      }),
                  SizedBox(width: _DIRECTION_SPACE),
                  _Button(
                      size: _DIRECTION_BUTTON_SIZE,
                      onTap: () {
                        Game.of(context).right();
                      }),
                ],
              ),
              SizedBox(height: _DIRECTION_SPACE),
              Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  _Button(
                      size: _DIRECTION_BUTTON_SIZE,
                      onTap: () {
                        Game.of(context).left();
                      }),
                  SizedBox(width: _DIRECTION_SPACE),
                  _Button(
                    size: _DIRECTION_BUTTON_SIZE,
                    onTap: () {
                      //Game.of(context).down();
                      Game.of(context).drop(); // todo 快速掉落
                    },
                  ),
                ],
              ),

            ],
          ),
        ),
      ],
    );

    return Column(
      mainAxisSize: MainAxisSize.max,
      children: <Widget>[
        SystemButtonGroup(),
        Expanded(
          child: Center(
            child: directView,
          ),
        )
      ],
    );;
  }
}


class SystemButtonGroup extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    var row = Row(
      children: <Widget>[
        // Spacer(flex: 1),
        _Description(
          text: "声音",
          child: _Button(
              size: _SYSTEM_BUTTON_SIZE,
              color: SYSTEMBTNColor,
              enableLongPress: false,
              onTap: () {
                Game.of(context).soundSwitch();
              }),
          isBigBtn: false ,
        ),

        SizedBox( width: 5,) ,

        _Description(
          text: "暂停/恢复",
          child: _Button(
              size: _SYSTEM_BUTTON_SIZE,
              color: SYSTEMBTNColor,
              enableLongPress: false,
              onTap: () {
                Game.of(context).pauseOrResume();
              }),
          isBigBtn: false ,
        ),
        SizedBox( width: 5,) ,
        _Description(
          text: "重置",
          child: _Button(
              size: _SYSTEM_BUTTON_SIZE,
              enableLongPress: false,
              color: Colors.red,
              onTap: () {
                Game.of(context).reset();
              }),
          isBigBtn: false ,
        )
      ],
    );

    return row ;
  }
}

class DropButton extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return _Description(
      text: '变化',
      child: _Button(
          enableLongPress: false,
          size: Size(90, 90),
          onTap: () {
            //Game.of(context).drop();
            Game.of(context).rotate();
          }),
      isBigBtn: true ,
    );
  }
}

class ChangeController extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    var column = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Spacer(flex: 5), // 按照比例分配 剩余的空间 ，弹性布局
        DropButton() ,
        Spacer(flex: 1),
      ],
    );

    return  column ;
  }
}

class _Button extends StatefulWidget {
  final Size size;
  final Widget icon;
  final VoidCallback onTap;
  ///the color of button
  final Color color;

  final bool enableLongPress;

  const _Button(
      {Key key,
      @required this.size,
      @required this.onTap,
      this.icon,
      this.color = Colors.blue,
      this.enableLongPress = true})
      : super(key: key);

  @override
  _ButtonState createState() {
    return new _ButtonState();
  }
}


class _Description extends StatelessWidget {
  final String text;
  final Widget child;
  final bool isBigBtn ;

  const _Description({  Key key, this.text, this.child, this.isBigBtn  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double txtSize = isBigBtn ? 20 :8 ;
    Widget  widget = Column(
      children: <Widget>[
        child,
        SizedBox(height: 8),
        Text(
          text,
          style: TextStyle(
              decoration: TextDecoration.none ,
              color:Colors.white ,
              fontSize: txtSize,
              fontStyle: FontStyle.italic,
              fontWeight: FontWeight.normal) ,
        ),
      ],
      mainAxisSize: MainAxisSize.min,
    );

    return widget ;
  }
}

class _ButtonState extends State<_Button> {
  Timer _timer;
  bool _tapEnded = false;
  Color _color;

  @override
  void didUpdateWidget(_Button oldWidget) {
    super.didUpdateWidget(oldWidget);
    _color = widget.color;
  }

  @override
  void initState() {
    super.initState();
    _color = widget.color;
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: _color,
      elevation: 2,
      shape: CircleBorder(),
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTapDown: (_) async {
          setState(() {
            // todo 按钮点击效果
            _color = widget.color.withOpacity(0.3);
          });
          if (_timer != null) {
            return;
          }
          _tapEnded = false;
          widget.onTap();
          if (!widget.enableLongPress) {
            return;
          }
          await Future.delayed(const Duration(milliseconds: 300));
          if (_tapEnded) {
            return;
          }
          _timer = Timer.periodic(const Duration(milliseconds: 60), (t) {
            if (!_tapEnded) {
              widget.onTap();
            } else {
              t.cancel();
              _timer = null;
            }
          });
        },
        onTapCancel: () {
          _tapEnded = true;
          _timer?.cancel();
          _timer = null;
          setState(() {
            _color = widget.color;
          });
        },
        onTapUp: (_) {
          _tapEnded = true;
          _timer?.cancel();
          _timer = null;
          setState(() {
            _color = widget.color;
          });
        },
        child: SizedBox.fromSize(
          size: widget.size,
        ),
      ),
    );
  }
}
